package com.demo.redpacket;

import com.demo.common.constant.ConstantSys;
import com.demo.common.dto.ReturnDto;
import com.demo.common.exception.BusinessException;
import com.demo.common.exception.NameRepeatException;
import com.demo.common.interceptor.ExceptionInterceptor;
import com.demo.common.model.People;
import com.demo.common.model.Redpacket;
import com.demo.common.tool.ToolDateTime;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class RedPacketController extends Controller {
	@Before(ExceptionInterceptor.class)
	public void index() {
		
	}
	
	public void toAdd() {
		render("add.html");
	}
	
	@Before({RedPacketValidator.class,Tx.class, ExceptionInterceptor.class})
	public void add() {
		Integer peopleId;
		//获取名称
		String name = getPara("name");
		People people = People.dao.findByName(name);
		if(people == null) {
			people = new People();
			people.setName(name);
			try {
				if(!people.save()) {
					throw new BusinessException("用户保存失败!请联系管理员");
				}
			} catch (ActiveRecordException e) {
				if(e.getCause().toString().indexOf("com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException") != -1) {
					throw new NameRepeatException("名称[" + name +"]已经存在,请勿重复添加!");
				}
			}
		}
		
		peopleId = people.getId();
		//获取红包对象
		Redpacket redpacket = getModel(Redpacket.class);
		
		//查看该用户是否已经记录过结婚红包
		Redpacket tmp = Redpacket.dao.findByPeopleAndType(peopleId, redpacket.getType());
		if(tmp != null) {
			throw new BusinessException(name + "已经记录过!如姓名相同，请更换姓名");
		}
		
		redpacket.setPeopleId(peopleId);
		redpacket.setCreateTime(ToolDateTime.format(ToolDateTime.getDate(), ToolDateTime.pattern_ymd_hms));
		redpacket.setStatus(ConstantSys.RED_STATUS_WH);
		if(!redpacket.save())
			throw new BusinessException("红包数据保存失败!请联系管理员");
		
		ReturnDto rdto = new ReturnDto();
		rdto.setSuccess(true);
		renderJson(rdto);
	}
	
	public void paginateToJson() {
		int pageNumber = getParaToInt("pageNumber", 1);
		int pageSize = getParaToInt("pageSize",20);
		
		renderJson(Redpacket.dao.paginate(pageNumber, pageSize));
	}
	

	public void toDetail() {
		setAttr("peopleId", getParaToInt());
		render("detail.html");
	}
	
	public void paginateByPeopleIdToJson() {
		int pageNumber = getParaToInt("pageNumber", 1);
		int pageSize = getParaToInt("pageSize",20);
		int peopleId = getParaToInt("peopleId");
		
		Page<Record> recordList = Redpacket.dao.paginateByPeople(pageNumber, pageSize, peopleId);

		renderJson(recordList);
	}
	
	public void toUpdate() {
		
		render("update.html");
	}
}
